package com.ruoyi.wechat.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.BusinessWechat;
import com.ruoyi.wechat.domain.Weather;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取天气数据
 *
 * @author xied
 */
@Component
public class WeatherUtil {
    public static AjaxResult getWeather(BusinessWechat businessWechat) {
        RestTemplate restTemplate = new RestTemplate();
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("district_id", businessWechat.getAkDistrictId());
        map.put("data_type", "all");
        map.put("ak", businessWechat.getAk());
        try {
            String paramsStr = toQueryString(map);
            String wholeStr = new String("/weather/v1/?" + paramsStr + "ntTMb8UD3SLEO8G40TyP830YG4RCU5Zd");
            String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
            String sn = MD5(tempStr);
            map.put("sn", sn);
        } catch (Exception e) {
            //
        }
        String res = HttpUtil.createGet("https://api.map.baidu.com/weather/v1/").form(map).execute().body();
        JSONObject json = JSONUtil.parseObj(res);
        // 获取接口响应状态
        String status = String.valueOf((Integer) json.get("status"));
        if (!"0".equals(status)) {
            // 响应状态不为0即调用出错
            String err = (String) json.get("message");
            return AjaxResult.error(status, "天气接口调用报错:" + err);
        }
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = JSONUtil.toList(forecasts, Weather.class);
        Weather weather = weathers.get(0);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        JSONObject location = json.getJSONObject("result").getJSONObject("location");
        weather.setText_now((String) now.get("text"));
        weather.setTemp(String.valueOf((Integer) now.get("temp")));
        weather.setCity((String) location.get("city"));
        weather.setCityName((String) location.get("name"));
        return AjaxResult.success(status, weather);
    }

    /**
     * 对Map内所有value作utf8编码，拼接返回结果
     */
    public static String toQueryString(LinkedHashMap<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8")).append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    // 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

}
